<script setup>
import { ref, computed } from 'vue'
import { onLoad } from '@dcloudio/uni-app';
import DishItem from '@/components/DishItem.vue'
import { getMerchantDetailAPI, getMerchantScoreAPI, submitMerchantScoreAPI } from '@/api/merchant'
import { useUserStore } from '@/stores'

// 店铺ID
const shopId = ref('1')
const shopInfo = ref({
  id: '',
  merchantName: '',
  image: '',
  location: '',
  merchantRating: 0,
  ratingCount: 0,
  businessMealsType: 0, // 0=早餐 1=午餐 2=晚餐
  dishList: []
})
const loading = ref(true)

// 用户评分
const userRating = ref(0)
const ratingTexts = ['极差', '失望', '一般', '满意', '惊喜']

// 营业类型映射
const mealTypeMap = ['早', '午', '晚','零食']

//处理拼接好的营业类型
const formatBusinessMealsType = (type) => {
  const ids =type
    .toString()
    .split('')
    .map((id) => parseInt(id))
    return ids
}

const businessMealTypeText = computed(() => {
  return formatBusinessMealsType(shopInfo.value.businessMealsType)
    .map(id => mealTypeMap[id-1] || '')
    .filter(Boolean)
    .join('、')
})

// 固定营业时间段（根据类型）
function getBusinessHours(type) {
  //含有1=早餐 2=午餐 3=晚餐 4=零食
  const types = formatBusinessMealsType(type)
  const timeSlots = {
    1: '06:00 - 10:00',
    2: '10:00 - 14:00',
    3: '16:00 - 20:00',
    4: '8:00 - 22:00'
  }
  const hours = types.map(t => timeSlots[t]).filter(Boolean)
  return hours.length ? hours.join(' / ') : '暂无营业时间'
}

// 营业状态计算
const businessStatus = computed(() => {
  const now = new Date()
  const currentHour = now.getHours()
  const currentMinute = now.getMinutes()
  const currentTime = currentHour * 60 + currentMinute

  // 根据营业类型获取时段
  let [openHour, closeHour] = getBusinessHours(shopInfo.value.businessMealsType).split(' - ').map(t => {
    const [h, m] = t.split(':').map(Number)
    return h * 60 + m
  })

  return currentTime >= openHour && currentTime <= closeHour 
    ? { status: '营业中', color: '#67C23A', icon: 'icon-zhengchang' }
    : { status: '已休息', color: '#F56C6C', icon: 'icon-xiuqi' }
})

// 评分文本
const getRatingText = computed(() => {
  if (userRating.value === 0) return ''
  const index = Math.ceil(userRating.value) - 1
  return ratingTexts[index] || ''
})

// 加载店铺详情
const loadShopDetail = async () => {
  loading.value = true
  try {
    const res = await getMerchantDetailAPI(shopId.value)
    if (res?.data) shopInfo.value = { ...shopInfo.value, ...res.data }
    else uni.showToast({ title: '店铺信息获取失败', icon: 'none' })
  } catch (error) {
    console.error('加载失败:', error)
    uni.showToast({ title: '加载失败，点击重试', icon: 'none' })
  } finally {
    loading.value = false
  }
}

// 加载用户已有评分
const loadUserRating = async () => {
  try {
    const userStore = useUserStore();
    if (userStore.isLoggedIn === false) {
      userRating.value = 0;  // 未登录时强制为0
      return uni.showToast({ title: '登录后可评分', icon: 'none' });
    }

    const res = await getMerchantScoreAPI(userStore.userInfo.id, shopInfo.value.id);
    // 确保评分是数字（0-5）
    userRating.value = res?.code === 1 && typeof res.data?.rating === 'number' 
      ? Number(res.data.rating) 
      : 0;
  } catch (error) {
    console.error('加载评分失败:', error);
    userRating.value = 0;  // 出错时强制为0
  }
};

// 提交评分
const submitRating = async () => {
  if (userRating.value === 0) {
    return uni.showToast({ title: '请先选择评分', icon: 'none' });
  }

  try {
    const userStore = useUserStore();
    if (userStore.isLoggedIn === false) {
      return uni.showToast({ title: '请先登录', icon: 'none' });
    }
    
    // 调用提交接口（merchantId 为店铺ID，rating 为当前评分）
    await submitMerchantScoreAPI(shopInfo.value.id, userRating.value);
    uni.showToast({ title: '评分成功，感谢反馈！', icon: 'success' });
    
    // 提交后刷新店铺评分和用户评分
    setTimeout(() => {
      loadShopDetail(); // 刷新店铺整体评分
      loadUserRating(); // 刷新用户当前评分
    }, 1000);
  } catch (error) {
    console.error('提交评分失败:', error);
    uni.showToast({ title: '提交失败，请稍后重试', icon: 'none' });
  }
};

// 页面初始化
onLoad((options) => {
  if (options?.id) {
    shopId.value = options.id
    loadShopDetail()
    setTimeout(loadUserRating, 500)
  }
})
</script>

<template>
  <view class="shop-detail-container">
    <!-- 店铺信息区域 -->
    <view class="shop-info-section">
      <!-- 加载状态 -->
      <view v-if="loading" class="loading-container">
        <view class="loading-spinner"></view>
        <text>加载中...</text>
      </view>
      
      <view v-else class="shop-header">
        <!-- 店铺图片 -->
        <view class="shop-image-container">
          <image
            :src="shopInfo.image"
            class="shop-image"
            mode="aspectFill"

            lazy-load
          />
        </view>

        <!-- 店铺基本信息 -->
        <view class="shop-basic-info">
          <view class="shop-title-row">
            <text class="shop-title">{{ shopInfo.merchantName }}</text>
            <view class="status-badge" :style="{ color: businessStatus.color }">
              <text class="iconfont" :class="businessStatus.icon"></text>
              {{ businessStatus.status }}
            </view>
          </view>

          <!-- 核心信息网格 -->
          <view class="info-grid">
            <view class="info-item">
              <text class="iconfont icon-weizhi"></text>
              <view class="info-content">
                <view class="info-label">位置</view>
                <view class="info-value">{{ shopInfo.location }}</view>
              </view>
            </view>

            <view class="info-item">
              <text class="iconfont icon-rili"></text>
              <view class="info-content">
                <view class="info-label">营业时间</view>
                <view class="info-value">{{ getBusinessHours(shopInfo.businessMealsType) }}</view>
              </view>
            </view>

            <view class="info-item">
              <text class="iconfont icon-icon"></text>
              <view class="info-content">
                <view class="info-label">综合评分</view>
                <view class="info-value">
                  <span class="score-number">{{ Number(shopInfo.merchantRating).toFixed(1) }}</span>
                  <uni-rate 
                    :value="shopInfo.merchantRating" 
                    :readonly="true" 
                    :size="18"
                    color="#ffd700"
                  />
                </view>
                <view class="info-detail">{{ shopInfo.ratingCount }} 人评价</view>
              </view>
            </view>

            <view class="info-item">
              <text class="iconfont icon-caipin"></text>
              <view class="info-content">
                <view class="info-label">菜品数量</view>
                <view class="info-value">{{ shopInfo.dishList?.length || 0 }} 道</view>
                <view class="info-detail">{{ businessMealTypeText }}</view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 用户评分区域 -->
    <view class="rating-section">
      <view class="rating-header">
        <text class="rating-title">
          <text class="iconfont icon-pingfen"></text>
          为这家店铺评分
        </text>
      </view>
      <view class="rating-content">
        <uni-rate 
          v-model="userRating" 
          :size="36"
          active-color="#FFB800"
          void-color="#F0F0F0"
          allow-half
          touchable
        />
        <text class="rating-text" v-if="getRatingText">{{ getRatingText }}</text>
        <button
          type="primary"
          @click="submitRating"
          :disabled="userRating === 0"
          class="submit-rating-btn"
        >
          提交评分
        </button>
      </view>
    </view>

    <!-- 店铺菜品区域 -->
    <view class="shop-dishes-section">
      <view class="dishes-header">
        <text class="dishes-title">
          商家菜品
        </text>
        <view class="dishes-count">
          {{ shopInfo.dishList?.length || 0 }} 道
        </view>
      </view>

      <!-- 菜品列表 -->
      <view class="dishes-list">
        <view v-if="!shopInfo.dishList?.length" class="no-dishes">
          <text class="iconfont icon-kongbai"></text>
          <text>暂无商家菜品信息</text>
        </view>
        <view v-else class="dish-grid">
          <view
            v-for="dish in shopInfo.dishList"
            :key="dish.id"
            class="dish-item-wrapper"
          >
            <DishItem :dish="dish" />
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<style scoped lang="scss">
.shop-detail-container {
  min-height: 100vh;
  background: #f5f7fa;
  padding: 30rpx 24rpx calc(80rpx + env(safe-area-inset-bottom)) 24rpx;
}

// 加载状态
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 100rpx 40rpx;
  color: #666;

  .loading-spinner {
    width: 60rpx;
    height: 60rpx;
    border: 6rpx solid rgba(102, 126, 234, 0.2);
    border-top: 6rpx solid #667eea;
    border-radius: 50%;
    animation: spin 1s linear infinite;
    margin-bottom: 24rpx;
  }
}

// 店铺信息区域
.shop-info-section {
  background: #fff;
  border-radius: 30rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.05);

  .shop-header {
    display: flex;
    gap: 24rpx;
    margin-bottom: 30rpx;
    flex-direction: column;

    .shop-image-container {
      width: 100%;
      height: 300rpx;

      .shop-image {
        width: 100%;
        height: 100%;
        border-radius: 20rpx;
        box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
      }
    }

    .shop-basic-info {
      .shop-title-row {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 24rpx;

        .shop-title {
          font-size: 36rpx;
          font-weight: 700;
          color: #333;
        }

        .status-badge {
          display: flex;
          align-items: center;
          gap: 6rpx;
          font-size: 26rpx;
          font-weight: 600;
        }
      }

      .info-grid {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 16rpx;

        .info-item {
          display: flex;
          align-items: flex-start;
          gap: 12rpx;
          padding: 16rpx;
          background: #f9f9f9;
          border-radius: 16rpx;

          > .iconfont {
            font-size: 28rpx;
            color: #667eea;
            margin-top: 2rpx;
          }

          .info-content {
            .info-label {
              font-size: 22rpx;
              color: #999;
              margin-bottom: 4rpx;
            }

            .info-value {
              font-size: 26rpx;
              font-weight: 600;
              color: #333;
              display: flex;
              align-items: center;
              gap: 8rpx;
            }

            .score-number {
              font-size: 28rpx;
              font-weight: 700;
              color: #ff9800;
            }

            .info-detail {
              font-size: 22rpx;
              color: #666;
            }
          }
        }
      }
    }
  }
}

// 用户评分区域
.rating-section {
  background: #fff;
  border-radius: 30rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.05);
  text-align: center;

  .rating-header {
    margin-bottom: 30rpx;

    .rating-title {
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 10rpx;
      font-size: 32rpx;
      color: #333;
      font-weight: 600;
    }
  }

  .rating-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 24rpx;

    .rating-text {
      font-size: 28rpx;
      color: #667eea;
      font-weight: 600;
    }

    .submit-rating-btn {
      background: linear-gradient(45deg, #667eea, #764ba2);
      border: none;
      padding: 18rpx 60rpx;
      font-weight: 600;
      border-radius: 30rpx;
      color: white;
      font-size: 26rpx;
      width: 60%;

      &[disabled] {
        background: #eee;
        color: #999;
      }
    }
  }
}

// 菜品区域
.shop-dishes-section {
  background: #fff;
  border-radius: 30rpx;
  padding: 30rpx;
  box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.05);

  .dishes-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 30rpx;
    padding-bottom: 15rpx;
    border-bottom: 1px solid #f0f0f0;

    .dishes-title {
      display: flex;
      align-items: center;
      gap: 10rpx;
      font-size: 32rpx;
      color: #333;
      font-weight: 600;
    }

    .dishes-count {
      font-size: 24rpx;
      color: #667eea;
      background: #f0f5ff;
      padding: 6rpx 18rpx;
      border-radius: 16rpx;
    }
  }

  .dishes-list {
    .no-dishes {
      text-align: center;
      padding: 80rpx 40rpx;
      color: #999;

      .iconfont {
        font-size: 80rpx;
        margin-bottom: 20rpx;
        display: block;
        color: #eee;
      }

      text {
        font-size: 26rpx;
      }
    }

    .dish-grid {
      display: grid;
      grid-template-columns: 1fr;
      gap: 20rpx;
    }

    .dish-item-wrapper {
      position: relative;
      animation: fadeIn 0.5s ease forwards;
    }
  }
}

// 动画
@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10rpx); }
  to { opacity: 1; transform: translateY(0); }
}

// 大屏适配
@media (min-width: 768rpx) {
  .shop-info-section .shop-header {
    flex-direction: row;
  }
  .shop-image-container {
    width: 40%;
    height: 240rpx;
  }
}
</style>